import { useSelected, useFocused } from "slate-react";
import isUrl from 'is-url';
import { Transforms} from 'slate'
import imageExtensions from 'image-extensions'
export type EmptyText = {
  text: string
}
type ImageElement = {
  type: 'image'
  url: string
  children: EmptyText[]
}
const Image = ({ attributes, children, element }) => {
  const selected = useSelected()
  const focused = useFocused()
  return (
    <div {...attributes}>
      <div contentEditable={false}>
        <img
          src={element.url}
          style={{
            display: 'block',
            boxShadow: selected && focused ? '0 0 0 3px #B4D5FF' : 'none',
            maxWidth: '100%',
            maxHeight: '20em'
          }}
        />
      </div>
      {children}
    </div>
  )
}

export function insertImage (editor, url) {
  const text = { text: '' }
  const image: ImageElement = { type: 'image', url, children: [text] }
  Transforms.insertNodes(editor, image)
}

export function isImageUrl(url) {
  if (!url) return false
  if (!isUrl(url)) return false
  const ext = new URL(url).pathname.split('.').pop()
  return imageExtensions.includes(ext)
}

export default Image;